package PrintAB;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyCondition4 {
    private String s = "B";
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    /**
     * ⽣产
     */
    public void printA() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while (!s.equals("B")) {
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            s = "A";
            System.out.println(Thread.currentThread().getName() + "\t " + s);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 消费
     */
    public void printB() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while (!s.equals("A")) {
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            s = "B";
            System.out.println(Thread.currentThread().getName() + "\t " + s);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

public class PrintByLock {

    public static void main(String[] args) {

        MyCondition4 myCondition4 = new MyCondition4();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition4.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "线程1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition4.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "线程2").start();

    }
}
